<template>
  <el-dialog
    v-model="dialogVisible"
    :title="note ? t('favorites.notes.editTitle') : t('favorites.notes.createTitle')"
    :width="isFullscreen ? '100%' : '80%'"
    :top="isFullscreen ? '0' : '8vh'"
    :fullscreen="isFullscreen"
    :before-close="handleBeforeClose"
    class="note-editor-dialog"
    center
  >
    <div class="editor-container">
      <div class="editor-header">
        <el-input 
          v-model="noteForm.title"
          :placeholder="t('favorites.notes.titlePlaceholder')"
          size="large"
          maxlength="200"
          show-word-limit
        />
        
        <div class="header-actions">
          <el-select
            v-model="noteForm.folderId"
            :placeholder="t('favorites.notes.selectFolder')"
            style="width: 150px"
          >
            <el-option :label="t('favorites.notes.defaultFolder')" :value="null" />
            <el-option
              v-for="folder in folders"
              :key="folder.id"
              :label="folder.name"
              :value="folder.id"
            />
          </el-select>

          <el-button
            :type="noteForm.isFavorite ? 'warning' : ''"
            :icon="Star"
            @click="noteForm.isFavorite = !noteForm.isFavorite"
          >
            {{ noteForm.isFavorite ? t('favorites.notes.favorited') : t('favorites.notes.addToFavorite') }}
          </el-button>

          <el-button
            :icon="FullScreen"
            @click="toggleFullscreen"
            :title="isFullscreen ? t('favorites.notes.exitFullscreenEdit') : t('favorites.notes.fullscreenEdit')"
          >
            {{ isFullscreen ? t('favorites.notes.exitFullscreen') : t('favorites.notes.fullscreen') }}
          </el-button>
        </div>
      </div>

      <!-- Markdown 编辑器 -->
      <div class="editor-content">
        <div class="md-editor-wrapper">
          <MdEditor
            v-model="noteForm.markdownContent"
            :placeholder="'支持Markdown语法，开始编写你的便签...'"
            :preview="true"
            :toolbars="toolbars"
            :theme="editorTheme"
            language="zh-CN"
            @onChange="handleContentChange"
            @onSave="handleSave"
          />
        </div>
      </div>

      <div class="editor-footer">
        <div class="footer-left">
          <el-tag
            v-for="tag in selectedTags"
            :key="tag.id"
            :type="getTagType(tag.color)"
            closable
            @close="handleRemoveTag(tag)"
            style="margin-right: 8px;"
          >
            {{ tag.name }}
          </el-tag>
          
          <el-button 
            size="small" 
            :icon="Plus"
            @click="showTagSelector = true"
          >
            {{ t('favorites.notes.addTag') }}
          </el-button>
        </div>

        <div class="shortcut-tips">
          <span class="tip-text">{{ t('favorites.notes.shortcuts') }}</span>
          <el-tag size="small" type="info">{{ t('favorites.notes.shortcutSave') }}</el-tag>
          <el-tag size="small" type="info">{{ t('favorites.notes.shortcutSaveClose') }}</el-tag>
          <el-tag size="small" type="info">{{ t('favorites.notes.shortcutClose') }}</el-tag>
        </div>

        <div class="footer-right">
          <el-button 
            :icon="Bell"
            @click="showReminderPicker = true"
          >
            {{ t('favorites.notes.setReminder') }}
          </el-button>
          <el-button @click="handleCancel">{{ t('favorites.dialogs.cancel') }}</el-button>
          <el-button
            type="primary"
            @click="handleSave"
            :loading="saving"
          >
            {{ t('favorites.notes.save') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 标签选择器 -->
    <el-dialog 
      v-model="showTagSelector"
      :title="t('favorites.notes.selectTags')"
      width="400px"
      append-to-body
    >
      <div class="tag-selector">
        <div class="available-tags">
          <el-tag
            v-for="tag in availableTags"
            :key="tag.id"
            :type="getTagType(tag.color)"
            :class="{ selected: isTagSelected(tag) }"
            @click="handleToggleTag(tag)"
            style="margin: 4px; cursor: pointer;"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        <div class="tag-actions">
          <el-button size="small" @click="showCreateTag = true">
            {{ t('favorites.notes.addTag') }}
          </el-button>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showTagSelector = false">{{ t('favorites.dialogs.confirm') }}</el-button>
      </template>
    </el-dialog>

    <!-- 提醒时间选择器 -->
    <el-dialog 
      v-model="showReminderPicker"
      :title="t('favorites.notes.setReminder')"
      width="400px"
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item :label="t('favorites.notes.reminderLabel')">
          <el-date-picker
            v-model="noteForm.reminderTime"
            type="datetime"
            :placeholder="t('favorites.notes.selectReminderTime')"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showReminderPicker = false">{{ t('favorites.dialogs.cancel') }}</el-button>
        <el-button
          type="primary"
          @click="showReminderPicker = false"
        >
          {{ t('favorites.dialogs.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Star, Plus, Bell, Document, FullScreen } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

// Props
interface Props {
  visible: boolean
  note?: any
  folders: any[]
  noteTags?: any[]
}

const props = defineProps<Props>()

// 国际化
const { t } = useI18n()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'save': [noteData: any]
}>()

// 响应式数据
const activeTab = ref('edit')
const saving = ref(false)
const showTagSelector = ref(false)
const showReminderPicker = ref(false)
const showCreateTag = ref(false)
const isFullscreen = ref(false)
const selectedTags = ref<any[]>([])

// Markdown 编辑器配置
const editorTheme = ref('light')
const toolbars = ref([
  'bold',
  'underline',
  'italic',
  '-',
  'title',
  'strikeThrough',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'task',
  '-',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'mermaid',
  'katex',
  '-',
  'revoke',
  'next',
  'save',
  '=',
  'pageFullscreen',
  'fullscreen',
  'preview',
  'htmlPreview',
  'catalog'
])

// 计算属性
const availableTags = computed(() => {
  return props.noteTags || [
    { id: 1, name: '重要', color: '#F56C6C' },
    { id: 2, name: '工作', color: '#409EFF' },
    { id: 3, name: '学习', color: '#67C23A' },
    { id: 4, name: '想法', color: '#E6A23C' }
  ]
})

const noteForm = reactive({
  title: '',
  markdownContent: '',
  content: '',
  folderId: null,
  isFavorite: false,
  reminderTime: null,
  tags: []
})

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
})

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 主题切换（可以根据系统主题自动切换）
watch(() => document.documentElement.classList.contains('dark'), (isDark) => {
  editorTheme.value = isDark ? 'dark' : 'light'
}, { immediate: true })

// 监听器
watch(() => props.note, (newNote) => {
  if (newNote) {
    noteForm.title = newNote.title || ''
    noteForm.markdownContent = newNote.markdownContent || ''
    noteForm.content = newNote.content || ''
    noteForm.folderId = newNote.folderId || null
    noteForm.isFavorite = newNote.isFavorite || false
    noteForm.reminderTime = newNote.reminderTime || null
    selectedTags.value = newNote.tags || []
  } else {
    // 重置表单
    noteForm.title = ''
    noteForm.markdownContent = ''
    noteForm.content = ''
    noteForm.folderId = null
    noteForm.isFavorite = false
    noteForm.reminderTime = null
    selectedTags.value = []
  }
}, { immediate: true })

// 监听对话框关闭，重置全屏状态
watch(() => props.visible, (newVisible) => {
  if (!newVisible) {
    isFullscreen.value = false
  }
})

// 事件处理
const handleContentChange = (value: string) => {
  // MdEditor 的 onChange 事件会传入新的内容
  noteForm.markdownContent = value
  noteForm.content = value // 保持兼容性
}

const handleBeforeClose = async (done: () => void) => {
  if (hasUnsavedChanges()) {
    try {
      await ElMessageBox.confirm(
        '有未保存的更改，确定要关闭吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      done()
    } catch (error) {
      // 用户取消
    }
  } else {
    done()
  }
}

const handleCancel = () => {
  visible.value = false
}

const handleSave = async () => {
  if (!noteForm.title.trim()) {
    ElMessage.warning('请输入便签标题')
    return
  }

  saving.value = true
  try {
    const noteData = {
      ...noteForm,
      tags: selectedTags.value
    }
    
    emit('save', noteData)
  } catch (error) {
    console.error('Failed to save note:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

const handleToggleTag = (tag: any) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
}

const handleRemoveTag = (tag: any) => {
  const index = selectedTags.value.findIndex(t => t.id === tag.id)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  }
}

const isTagSelected = (tag: any) => {
  return selectedTags.value.some(t => t.id === tag.id)
}

// 根据颜色获取标签类型，适配暗色主题
const getTagType = (color: string) => {
  if (!color) return ''

  // 根据颜色值映射到Element Plus的标签类型
  const colorMap: { [key: string]: string } = {
    '#F56C6C': 'danger',
    '#E6A23C': 'warning',
    '#67C23A': 'success',
    '#409EFF': 'primary',
    '#909399': 'info'
  }

  return colorMap[color] || ''
}

const hasUnsavedChanges = () => {
  // TODO: 实现变更检测逻辑
  return noteForm.title || noteForm.markdownContent
}

// 快捷键处理
const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl+S 或 Cmd+S 保存
  if ((event.ctrlKey || event.metaKey) && event.key === 's') {
    event.preventDefault()
    handleSave()
    ElMessage.success('快捷键保存成功 (Ctrl+S)')
  }

  // Ctrl+Enter 或 Cmd+Enter 保存并关闭
  if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
    event.preventDefault()
    handleSave()
  }

  // Esc 关闭对话框
  if (event.key === 'Escape' && !saving.value) {
    handleCancel()
  }
}

// 生命周期
onMounted(() => {
  // 添加全局键盘事件监听
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  // 移除全局键盘事件监听
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
/* 普通模式 */
.note-editor-dialog :deep(.el-dialog) {
  margin-top: 8vh;
  margin-bottom: 8vh;
  height: 84vh;
  display: flex;
  flex-direction: column;
}

/* 全屏模式 */
.note-editor-dialog :deep(.el-dialog.is-fullscreen) {
  margin: 0;
  height: 100vh;
}

.note-editor-dialog :deep(.el-dialog__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

.editor-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
}

.editor-header .el-input {
  flex: 1;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  padding: 16px 0;  /* 增加一些内边距 */
}

.md-editor-wrapper {
  height: 60vh;  /* 使用视口高度，更加灵活 */
  min-height: 600px;  /* 最小高度增加到 600px */
  max-height: 80vh;  /* 最大高度限制 */
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
}

.md-editor-wrapper :deep(.md-editor) {
  height: 100%;
}

.md-editor-wrapper :deep(.md-editor-input-wrapper) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.6;
}

.md-editor-wrapper :deep(.md-editor-preview-wrapper) {
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
}

/* 全屏模式下的编辑器优化 */
.note-editor-dialog :deep(.el-dialog.is-fullscreen) .md-editor-wrapper {
  height: calc(100vh - 200px);  /* 全屏时占据更多空间 */
  min-height: 700px;
  max-height: none;
}

.empty-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--el-text-color-secondary);
  gap: 8px;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-top: 1px solid var(--el-border-color);
}

.footer-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.footer-right {
  display: flex;
  gap: 8px;
}

.shortcut-tips {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  margin: 0 16px;
}

.tip-text {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-right: 4px;
}

.shortcut-tips .el-tag {
  font-size: 11px;
  padding: 2px 6px;
}

.tag-selector {
  min-height: 200px;
}

.available-tags {
  margin-bottom: 16px;
}

.available-tags .el-tag {
  transition: all 0.2s;
}

.available-tags .el-tag:hover {
  transform: scale(1.05);
}

.available-tags .el-tag.selected {
  border: 2px solid var(--el-color-primary);
}

.tag-actions {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .note-editor-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 2vh auto;
    height: 96vh;
  }

  .md-editor-wrapper {
    height: 50vh;
    min-height: 400px;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .shortcut-tips {
    display: none; /* 在小屏幕上隐藏快捷键提示 */
  }
}

@media (min-width: 1200px) {
  .md-editor-wrapper {
    min-height: 700px; /* 大屏幕上更高的最小高度 */
  }
}
</style>
